<?php
namespace app\controller\voice;

use app\BaseController;
use think\App;
use app\service\TopviewApiService;
use think\facade\Db;
use app\service\PointsService;

class VoiceClone extends BaseController
{
    protected $apiService;

    public function __construct(App $app)
    {
        $this->apiService = new TopviewApiService();
        parent::__construct($app);
    }

    // 提交声音克隆任务
    public function submit()
    {
        try {
            $userId = $this->request->user->uid;
            $params = input('post.');

            // 积分校验与扣减：克隆一次扣除200积分
            $pointsService = new PointsService();
            $needPoints = 30;
            $userPoints = $pointsService->getUserPoints($userId);
            if ($userPoints < $needPoints) {
                return json(['code' => 400, 'msg' => "积分不足，需要{$needPoints}积分，当前余额{$userPoints}积分", 'data' => null]);
            }
 
            $params['voiceText'] = "大家好，今天给大家推荐这款高颜值又实用的杯子。它采用食品级材质，安全环保，无异味；杯体设计简约大方，颜值担当，无论是办公室、居家还是外出携带都超有范儿。大容量设计，不论是泡茶、咖啡、奶茶还是果汁统统hold住。杯口圆润，手感舒适，杯盖密封不漏水，让你怎么用都安心。现在下单，还有多种颜色可以选择，总有一款适合你！";
            $result = $this->apiService->submitVoiceCloneTask($params);

            // 提交成功后扣除积分
            $pointsService->consume($userId, $needPoints, '声音克隆');

            Db::name('voice_clone_tasks')->insert([
                'user_id' => $userId,
                'task_id' => $result['taskId'] ?? '',
                'audio_file_id' => $params['audioFileId'] ?? ($params['fileId'] ?? null),
                'name' => $params['name'] ?? null,
                'status' => 1,
                'create_time' => date('Y-m-d H:i:s'),
                'points' => $needPoints
            ]);

            return json(['code' => 200, 'msg' => 'success', 'data' => $result]);
        } catch (\Exception $e) {
            \think\facade\Log::error($e->getMessage());
            return json(['code' => 500, 'msg' => $e->getMessage(), 'data' => null]);
        }
    }

    // 查询声音克隆任务
    public function query()
    {
        try {
            $userId = $this->request->user->uid;
            $taskId = input('taskId');
            if (empty($taskId)) {
                return json(['code' => 400, 'msg' => 'taskId不能为空', 'data' => null]);
            }

            $result = $this->apiService->queryVoiceCloneTask($taskId);

            $update = [];
            if (isset($result['status'])) {
                $statusMap = ['init' => 0, 'running' => 1, 'success' => 2, 'failed' => 3];
                $update['status'] = $statusMap[$result['status']] ?? 1;
            }
            if (!empty($result['voiceId'])) {
                $update['voice_id'] = $result['voiceId'];
            }
            if (!empty($result['errorMsg'])) {
                $update['error_msg'] = $result['errorMsg'];
            }
            if (!empty($update)) {
                $update['update_time'] = date('Y-m-d H:i:s');
                Db::name('voice_clone_tasks')
                    ->where('task_id', $taskId)
                    ->where('user_id', $userId)
                    ->update($update);
            }

            return json(['code' => 200, 'msg' => 'success', 'data' => $result]);
        } catch (\Exception $e) {
            \think\facade\Log::error('VoiceClone query error', ['error' => $e->getMessage(), 'trace' => $e->getTraceAsString()]);
            return json(['code' => 500, 'msg' => $e->getMessage(), 'data' => null]);
        }
    }

    // 获取我的声音克隆任务列表
    public function list()
    {
        try {
            $userId = $this->request->user->uid;
            $page = intval(input('page', 1));
            $pageSize = intval(input('pageSize', 10));

            $list = Db::name('voice_clone_tasks')
                ->where('user_id', $userId)
                ->order('id', 'desc')
                ->page($page, $pageSize)
                ->select()
                ->each(function($item) {
                    $statusMap = [0 => '待处理', 1 => '处理中', 2 => '成功', 3 => '失败'];
                    $item['status_code'] = $item['status'];
                    $item['status'] = $statusMap[$item['status']] ?? '未知';
                    return $item;
                });

            $total = Db::name('voice_clone_tasks')
                ->where('user_id', $userId)
                ->count();

            return json([
                'code' => 200,
                'msg' => 'success',
                'data' => [
                    'list' => $list,
                    'pagination' => [
                        'page' => $page,
                        'pageSize' => $pageSize,
                        'total' => $total,
                        'totalPages' => ceil($total / $pageSize)
                    ]
                ]
            ]);
        } catch (\Exception $e) {
            \think\facade\Log::error('VoiceClone list error', ['error' => $e->getMessage(), 'trace' => $e->getTraceAsString()]);
            return json(['code' => 500, 'msg' => $e->getMessage(), 'data' => null]);
        }
    }

    // 删除音色
    public function delete()
    {
        try {
            $userId = $this->request->user->uid;
            $taskId = input('taskId');
            
            if (empty($taskId)) {
                return json(['code' => 400, 'msg' => 'taskId不能为空', 'data' => null]);
            }

            // 删除任务记录
            $result = Db::name('voice_clone_tasks')
                ->where('id', $taskId)
                ->where('user_id', $userId)
                ->delete();

            if ($result) {
                return json(['code' => 200, 'msg' => '删除成功', 'data' => null]);
            } else {
                return json(['code' => 500, 'msg' => '删除失败', 'data' => null]);
            }

        } catch (\Exception $e) {
            \think\facade\Log::error('voice_clone_tasks delete error', ['error' => $e->getMessage(), 'trace' => $e->getTraceAsString()]);
            return json(['code' => 500, 'msg' => $e->getMessage(), 'data' => null]);
        }
    }
}


